from django import forms
from django_summernote.widgets import SummernoteWidget
from .models import Post, Comment, Category, Tag


class PostForm(forms.ModelForm):
    """博客文章表单"""

    class Meta:
        model = Post
        fields = ['title', 'content', 'summary', 'category', 'tags', 'featured_image', 'status', 'publish_date']
        widgets = {
            'content': SummernoteWidget(),
            'summary': forms.Textarea(attrs={'rows': 3}),
            'publish_date': forms.DateTimeInput(attrs={'type': 'datetime-local'}),
        }

    def clean_title(self):
        """确保标题不为空"""
        title = self.cleaned_data.get('title')
        if not title:
            raise forms.ValidationError("标题不能为空")
        return title


class CommentForm(forms.ModelForm):
    """评论表单"""

    class Meta:
        model = Comment
        fields = ['content']
        widgets = {
            'content': forms.Textarea(attrs={'rows': 4, 'placeholder': '写下你的评论...', 'id': 'id_content'}),
        }
        labels = {
            'content': '',
        }


class ReplyForm(forms.ModelForm):
    """回复表单"""

    class Meta:
        model = Comment
        fields = ['content']
        widgets = {
            'content': forms.Textarea(attrs={'rows': 2, 'placeholder': '写下你的回复...', 'class': 'form-control'}),
        }
        labels = {
            'content': '',
        }


class CategoryForm(forms.ModelForm):
    """分类表单"""

    class Meta:
        model = Category
        fields = ['name', 'description']
        widgets = {
            'name': forms.TextInput(attrs={'class': 'form-control', 'placeholder': '分类名称'}),
            'description': forms.Textarea(attrs={'class': 'form-control', 'rows': 3, 'placeholder': '分类描述（可选）'}),
        }

    def clean_name(self):
        name = self.cleaned_data.get('name')
        if Category.objects.filter(name=name).exists():
            raise forms.ValidationError("该分类名称已存在")
        return name

    def save(self, commit=True):
        category = super().save(commit=False)
        # 自动生成slug
        from django.utils.text import slugify
        category.slug = slugify(category.name)

        # 确保slug唯一
        base_slug = category.slug
        counter = 1
        while Category.objects.filter(slug=category.slug).exists():
            category.slug = f"{base_slug}-{counter}"
            counter += 1

        if commit:
            category.save()
        return category


class TagForm(forms.ModelForm):
    """标签表单"""

    class Meta:
        model = Tag
        fields = ['name']
        widgets = {
            'name': forms.TextInput(attrs={'class': 'form-control', 'placeholder': '标签名称'}),
        }

    def clean_name(self):
        name = self.cleaned_data.get('name')
        if Tag.objects.filter(name=name).exists():
            raise forms.ValidationError("该标签名称已存在")
        return name

    def save(self, commit=True):
        tag = super().save(commit=False)
        # 自动生成slug
        from django.utils.text import slugify
        tag.slug = slugify(tag.name)

        # 确保slug唯一
        base_slug = tag.slug
        counter = 1
        while Tag.objects.filter(slug=tag.slug).exists():
            tag.slug = f"{base_slug}-{counter}"
            counter += 1

        if commit:
            tag.save()
        return tag

